package com.maiji.cloud.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.maiji.cloud.config.MyRedisConfig;
import com.maiji.cloud.entities.community.ComComment;
import com.maiji.cloud.entities.community.ComMsgInfo;
import com.maiji.cloud.entities.login.AppUser;
import com.maiji.cloud.entities.login.UserInfo;
import com.maiji.cloud.mapper.ComCommentMapper;
import com.maiji.cloud.mapper.ComMsgInfoMapper;
import com.maiji.cloud.microservice.UserInfoService;
import com.maiji.cloud.request.BaseInputDto;
import com.maiji.cloud.request.IdInputDto;
import com.maiji.cloud.request.ReqMetaData;
import com.maiji.cloud.request.community.ComAtWhoInputDto;
import com.maiji.cloud.request.community.ComCommentMsgInputDto;
import com.maiji.cloud.request.community.ComUserMessageInputDto;
import com.maiji.cloud.request.shopingmall.DistributeIntegralReqDto;
import com.maiji.cloud.response.*;
import com.maiji.cloud.response.community.ComCommentOutputDto;
import com.maiji.cloud.response.login.UserInfoResData;
import com.maiji.cloud.response.shopingmall.FinancialDetailsResData;
import com.maiji.cloud.service.*;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.maiji.cloud.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import java.text.MessageFormat;
import java.util.*;
import java.util.stream.Collectors;
import static org.springframework.beans.BeanUtils.*;

@Service
@Transactional
public class ComCommentServiceImpl extends ServiceImpl<ComCommentMapper, ComComment> implements ComCommentService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private ComMsgInfoMapper msgInfoMapper;

    @Autowired
    CommunityService communityService;

    @Autowired
    ComPraiseService praiseService;

    @Autowired
    ComCommentMapper comCommentMapper;

    @Autowired
    AsyncService asyncService;

    @Autowired
    IntegralService integralService;

    /**
     *
     * 社区评论通用接口
     * @param inputDto
     * @param maijiToken
     * @return
     */
    public BaseOutPutDto<FinancialDetailsResData> comment(@RequestBody BaseInputDto<ComCommentMsgInputDto>inputDto, @RequestHeader("maijiToken")String maijiToken){

        ComCommentMsgInputDto commentInputDto = inputDto.getData();
        switch (commentInputDto.getStatus()){
            case 0:
                return commentMsg(inputDto,maijiToken);
            case 1:
                return transmitMsg(inputDto,maijiToken);
            case 2:
                return commentComment(inputDto,maijiToken);
            case 3:
                return commentReply(inputDto,maijiToken);
            default:
                BaseOutPutDto<FinancialDetailsResData> outPutDto = new BaseOutPutDto<>();
                outPutDto.setStatus(Status.PARAMETERERROR);
                return outPutDto;
        }
    }

    /**
     * 评论动态
     * @param inputDto
     * @param maijiToken
     * @return
     */
    public BaseOutPutDto<FinancialDetailsResData>commentMsg(@RequestBody BaseInputDto<ComCommentMsgInputDto> inputDto,@RequestHeader("maijiToken")String maijiToken){
        BaseOutPutDto<FinancialDetailsResData> outPutDto = new BaseOutPutDto<>();
        AppUser appUser = RedisUtil.getAppUserByRedis(redisTemplate, MyRedisConfig.REDISDATABASENO, maijiToken, userInfoService);
        String userId = appUser.getUuId();

        try {
            ComCommentMsgInputDto commentMsgInputDto = inputDto.getData();
            if(StringUtils.isBlank(commentMsgInputDto.getContent())){
                outPutDto.setStatus(Status.ERROR);
                outPutDto.setMessage("内容不可以为空");
                return outPutDto;
            }
            if(!WXUtil.examineText(commentMsgInputDto.getContent())){
                outPutDto.setStatus(Status.NON_COMPLIANCE);
                return outPutDto;
            }

            ComMsgInfo msgInfo = msgInfoMapper.selectById(commentMsgInputDto.getBelongId());
            ComComment comment = new ComComment();
            copyProperties(inputDto.getData(),comment);
            comment.setCommentId(UUID_MD5.getUUID())
                    .setPublishTime(TimeUtil.getCurDateStamp())
                    .setSourceUserId(userId)
                    .setTargetUserId(msgInfo.getUserId())
                    .setStatus(0)
                    .setMsgId(msgInfo.getMsgId());
            if(comCommentMapper.insert(comment)>0) {
                msgInfo.setCommented_count(msgInfo.getCommented_count()+1);
                msgInfoMapper.updateById(msgInfo);

                {
                    ComUserMessageInputDto messageInputDto = new ComUserMessageInputDto();
                    messageInputDto.setCurCommentId(comment.getCommentId());
                    messageInputDto.setContent(comment.getContent());
                    messageInputDto.setSourceUserId(userId);
                    messageInputDto.setTargetUserId(comment.getTargetUserId());
                    messageInputDto.setType(ComUserMessageTypeEnum.Comment.getValue());
                    messageInputDto.setMsgId(comment.getMsgId());
                    asyncService.asycCreateMessage(messageInputDto);

                }

                outPutDto.setData(integral(comment,maijiToken));

            }
            createAtList(msgInfo.getMsgId(),comment.getCommentId(),comment.getContent(),commentMsgInputDto.getAtList(),userId);

            return outPutDto;
        }catch (Exception exc){
            outPutDto.setStatus(Status.ERROR);
            outPutDto.setMessage(exc.getMessage());
            return outPutDto;
        }

    }

    /**
     * 转发动态
     * @param inputDto
     * @param maijiToken
     * @return
     */
    public BaseOutPutDto<FinancialDetailsResData>transmitMsg(@RequestBody BaseInputDto<ComCommentMsgInputDto>inputDto,@RequestHeader("maijiToken")String maijiToken){
        BaseOutPutDto<FinancialDetailsResData> outPutDto = new BaseOutPutDto<>();
        AppUser appUser = RedisUtil.getAppUserByRedis(redisTemplate, MyRedisConfig.REDISDATABASENO, maijiToken, userInfoService);
        String userId = appUser.getUuId();
        try {
            ComCommentMsgInputDto commentMsgInputDto = inputDto.getData();

            if(! WXUtil.examineText(commentMsgInputDto.getContent())){
                outPutDto.setStatus(Status.NON_COMPLIANCE);
                return outPutDto;
            }

            ComMsgInfo msgInfo = msgInfoMapper.selectById(commentMsgInputDto.getBelongId());

            ComComment comment = new ComComment();
            copyProperties(inputDto.getData(),comment);
            comment.setCommentId(UUID_MD5.getUUID())
                    .setPublishTime(TimeUtil.getCurDateStamp())
                    .setSourceUserId(userId)
                    .setTargetUserId(msgInfo.getUserId())
                    .setStatus(1)
                    .setMsgId(msgInfo.getMsgId());
            if(comCommentMapper.insert(comment)>0){
                msgInfo.setTransmit_count(msgInfo.getTransmit_count()+1);
                msgInfoMapper.updateById(msgInfo);

                outPutDto.setData(integral(comment,maijiToken));

            }
            createAtList(msgInfo.getMsgId(),comment.getCommentId(),comment.getContent(),commentMsgInputDto.getAtList(),userId);
            return outPutDto;
        }catch (Exception exc){
            outPutDto.setStatus(Status.ERROR);
            outPutDto.setMessage(exc.getMessage());
            return outPutDto;
        }

    }

    /**
     * 评论其它评论
     * @param inputDto
     * @param maijiToken
     * @return
     */
    public BaseOutPutDto<FinancialDetailsResData>commentComment(BaseInputDto<ComCommentMsgInputDto> inputDto,@RequestHeader("maijiToken")String maijiToken){
        BaseOutPutDto<FinancialDetailsResData> outPutDto = new BaseOutPutDto<>();
        AppUser appUser = RedisUtil.getAppUserByRedis(redisTemplate, MyRedisConfig.REDISDATABASENO, maijiToken, userInfoService);
        String userId = appUser.getUuId();

        try {
            ComCommentMsgInputDto commentMsgInputDto = inputDto.getData();
            if(StringUtils.isBlank(commentMsgInputDto.getContent())){
                outPutDto.setStatus(Status.ERROR);
                outPutDto.setMessage("内容不可以为空");
                return outPutDto;
            }
            if(! WXUtil.examineText(commentMsgInputDto.getContent())){
                outPutDto.setStatus(Status.NON_COMPLIANCE);
                return outPutDto;
            }
            ComComment comment= comCommentMapper.selectById(commentMsgInputDto.getBelongId());

            ComComment sub = new ComComment();
            copyProperties(inputDto.getData(),sub);
            sub.setCommentId(UUID_MD5.getUUID())
                    .setPublishTime(TimeUtil.getCurDateStamp())
                    .setSourceUserId(userId)
                    .setTargetUserId(comment.getSourceUserId())
                    .setStatus(2)
                    .setMsgId(comment.getMsgId());

            if(comCommentMapper.insert(sub) > 0){
                {
                    ComUserMessageInputDto messageInputDto = new ComUserMessageInputDto();
                    messageInputDto.setCurCommentId(sub.getCommentId());
                    messageInputDto.setContent(sub.getContent());
                    messageInputDto.setSourceUserId(userId);
                    messageInputDto.setTargetUserId(sub.getTargetUserId());
                    messageInputDto.setType(ComUserMessageTypeEnum.CommentComment.getValue());
                    messageInputDto.setLastCommentId(comment.getCommentId());
                    messageInputDto.setMsgId(sub.getMsgId());
                    asyncService.asycCreateMessage(messageInputDto);

                }

                outPutDto.setData(integral(comment,maijiToken));
            }
            createAtList(comment.getMsgId(),sub.getCommentId(),sub.getContent(),commentMsgInputDto.getAtList(),userId);
            return outPutDto;
        }catch (Exception exc){
            return outPutDto;
        }
    }

    /**
     * 评论回复
     * @param inputDto
     * @param maijiToken
     * @return
     */
    public BaseOutPutDto<FinancialDetailsResData>commentReply(@RequestBody BaseInputDto<ComCommentMsgInputDto>inputDto,@RequestHeader("maijiToken")String maijiToken){

        BaseOutPutDto<FinancialDetailsResData> outPutDto = new BaseOutPutDto<>();
        AppUser appUser = RedisUtil.getAppUserByRedis(redisTemplate, MyRedisConfig.REDISDATABASENO, maijiToken, userInfoService);
        String userId = appUser.getUuId();

        try {
            ComCommentMsgInputDto commentMsgInputDto = inputDto.getData();
            if(StringUtils.isBlank(commentMsgInputDto.getContent())){
                outPutDto.setStatus(Status.ERROR);
                outPutDto.setMessage("内容不可以为空");
                return outPutDto;
            }
            if(!WXUtil.examineText(commentMsgInputDto.getContent())){
                outPutDto.setStatus(Status.NON_COMPLIANCE);
                return outPutDto;
            }
            ComComment comment= comCommentMapper.selectById(commentMsgInputDto.getBelongId());

            ComComment sub = new ComComment();
            copyProperties(inputDto.getData(),sub);
            sub.setCommentId(UUID_MD5.getUUID())
                    .setPublishTime(TimeUtil.getCurDateStamp())
                    .setSourceUserId(userId)
                    .setTargetUserId(comment.getSourceUserId())
                    .setStatus(3)
                    .setBelongId(comment.getBelongId())
                    .setMsgId(comment.getMsgId());

            if(comCommentMapper.insert(sub)>0){
                {
                    ComUserMessageInputDto messageInputDto = new ComUserMessageInputDto();
                    messageInputDto.setCurCommentId(sub.getCommentId());
                    messageInputDto.setContent(sub.getContent());
                    messageInputDto.setSourceUserId(userId);
                    messageInputDto.setTargetUserId(sub.getTargetUserId());
                    messageInputDto.setType(ComUserMessageTypeEnum.Reply.getValue());
                    messageInputDto.setMsgId(sub.getMsgId());
                    messageInputDto.setLastCommentId(comment.getCommentId());
                    asyncService.asycCreateMessage(messageInputDto);

                }

                outPutDto.setData(integral(comment,maijiToken));
            }
            createAtList(comment.getMsgId(),sub.getCommentId(),sub.getContent(),commentMsgInputDto.getAtList(),userId);
            return outPutDto;
        }catch (Exception exc){
            return outPutDto;
        }
    }

    /**
     * 评论列表
     * @param inputDto
     * @param maijiToken
     * @return
     */
    public BaseOutPutDto<List<ComCommentOutputDto>>commentList(BaseInputDto<IdInputDto>inputDto,@RequestHeader("maijiToken")String maijiToken){
        BaseOutPutDto<List<ComCommentOutputDto>> outPutDto = new BaseOutPutDto<>();
        String userId = "";
        if(!StringUtil.isBlank(maijiToken)){
            AppUser appUser = RedisUtil.getAppUserByRedis(redisTemplate, MyRedisConfig.REDISDATABASENO, maijiToken, userInfoService);
            if(appUser != null){
                userId = appUser.getUuId();
            }
        }
        try{
            IdInputDto idInputDto = inputDto.getData();
            ReqMetaData metaData = inputDto.getMetaData();
            String msgId = idInputDto.getId();
            List<ComComment> comments = comCommentMapper.commentList(msgId,userId,(metaData.getPage() - 1) * metaData.getSize(),metaData.getSize());

            ComMsgInfo msgInfo = communityService.selectById(msgId);

            List<ComCommentOutputDto> commentOutputDtos = recursionComments(comments,userId,msgInfo.getUserId());
            outPutDto.setData(commentOutputDtos);
            outPutDto.setStatus(Status.SUCCESS);
        }catch (Exception exc){
            outPutDto.setStatus(Status.ERROR);
            outPutDto.setMessage(exc.getMessage());
        }
        return outPutDto;

    }

    private List<ComCommentOutputDto> recursionComments(List<ComComment>comments,String userId,String authorId){
        List<ComCommentOutputDto> commentOutputDtos = new ArrayList<>();
        for (ComComment comment:comments
        ) {
            ComCommentOutputDto commentOutputDto = new ComCommentOutputDto();
            UserInfoResData source = new UserInfoResData();
            UserInfoResData target = new UserInfoResData();
            copyProperties(comment.getTargetUser(),target);
            copyProperties(comment.getSourceUser(),source);
            commentOutputDto.setTargetUser(target)
                    .setSourceUser(source);
            copyProperties(comment,commentOutputDto);

            if(comment.getSourceUserId().equals(userId)){
                commentOutputDto.setIsOfSelf(true);
            }
            if(authorId.equals(comment.getSourceUserId())){
                commentOutputDto.setIsAuthor(true);
            }

            if(comment.getPraise() != null)commentOutputDto.setIsPraise(true);
            if(comment.getCommentList() != null && comment.getCommentList().size()>0){
                List<ComCommentOutputDto> sub = recursionComments(comment.getCommentList(),userId,authorId);
                commentOutputDto.setCommentList(sub);
            }
            commentOutputDtos.add(commentOutputDto);
        }
        return commentOutputDtos;
    }

    /**
     * 评论点赞
     * @param maijiToken
     * @return
     */
    public BaseOutPutDto<String> commentPraise(BaseInputDto<IdInputDto> inputDto, @RequestHeader("maijiToken")String maijiToken){

        BaseOutPutDto<String> baseOutPutDto = new BaseOutPutDto<>();
        try{
            BaseOutPutDto praiseOutPutDto = praiseService.praise(inputDto,maijiToken);
            if(praiseOutPutDto.getStatus().equals(Status.SUCCESS)){
                ComComment comment= comCommentMapper.selectById(inputDto.getData().getId());
                comment.setPraise_count(comment.getPraise_count()+1);
                comCommentMapper.updateById(comment);
                baseOutPutDto.setStatus(Status.SUCCESS);
            }
            return baseOutPutDto;
        }catch (Exception exc){
            baseOutPutDto.setStatus(Status.ERROR);
            return baseOutPutDto;
        }
    }

    /**
     * 取消评论点赞
     * @param inputDto
     * @param maijiToken
     * @return
     */
    public BaseOutPutDto<String> cancelCommentPraise(BaseInputDto<IdInputDto>inputDto,@RequestHeader("maijiToken")String maijiToken){
        BaseOutPutDto<String> baseOutPutDto = new BaseOutPutDto<>();
        try{
            BaseOutPutDto praiseOutPutDto = praiseService.praise(inputDto,maijiToken);
            if(praiseOutPutDto.getStatus().equals(Status.SUCCESS)){
                ComComment comment= comCommentMapper.selectById(inputDto.getData().getId());
                comment.setPraise_count(comment.getPraise_count()-1);
                comCommentMapper.updateById(comment);
                baseOutPutDto.setStatus(Status.SUCCESS);
            }
            return baseOutPutDto;
        }catch (Exception exc){
            baseOutPutDto.setStatus(Status.ERROR);
            return baseOutPutDto;
        }
    }

    private FinancialDetailsResData integral(ComComment comment, String maijiToken){
        {
            try{

                //用户每天第一次评论 有积分
                EntityWrapper<ComComment> entityWrapper = new EntityWrapper<>();
                ComComment countComment = new ComComment();
                countComment.setSourceUserId(comment.getSourceUserId());
                entityWrapper.setEntity(countComment);
                Long startTime = TimeUtil.getZeroTime(new Date()).getTime();
                Long endTime = TimeUtil.getCurDateStamp();
                entityWrapper.where(MessageFormat.format("publish_time >= {0} and {1} >= publish_time",startTime.toString() ,endTime.toString()));
                if(comCommentMapper.selectCount(entityWrapper) == 1){
                    DistributeIntegralReqDto distributeIntegralReqDto = new DistributeIntegralReqDto();
                    DistributeIntegralReqDto.DistributeIntegralReqData distributeIntegralReqData = distributeIntegralReqDto.dataInstance();
                    distributeIntegralReqData.setRemark(FlowTypeEnum.REVIEW);
                    distributeIntegralReqData.setRelevantId(comment.getCommentId());
                    distributeIntegralReqDto.setData(distributeIntegralReqData);
                    return integralService.distributeIntegralByRemarkInt(distributeIntegralReqDto,maijiToken).getData();
                }
            }catch (Exception exc){

            }
            return null;
        }
    }

    /**
     * 评论删除 用于前端
     * @param inputDto
     * @param maijiToken
     * @return
     */
    public BaseOutPutDto<String> commentdelete(BaseInputDto<IdInputDto>inputDto,String maijiToken){
        BaseOutPutDto<String> outPutDto = new BaseOutPutDto();
        try{
            String userId = "";
            if(!StringUtil.isBlank(maijiToken)){
                AppUser appUser = RedisUtil.getAppUserByRedis(redisTemplate, MyRedisConfig.REDISDATABASENO, maijiToken, userInfoService);
                if(appUser != null){
                    userId = appUser.getUuId();
                }
            }

            Integer deletee = 0;
            String reason = "";
            ComComment comment = selectById(inputDto.getData().getId());
            if(comment != null){
                ComMsgInfo msgInfo = communityService.selectById(comment.getMsgId());
                if(msgInfo.getUserId().equals(userId)){
                    deletee = ComDeleteReasonEnum.AuthorDelete.getValue();
                    reason = ComDeleteReasonEnum.AuthorDelete.getMessage();
                }
                if(comment.getSourceUserId().equals(userId)){
                    deletee = ComDeleteReasonEnum.UserDelete.getValue();
                    reason = ComDeleteReasonEnum.UserDelete.getMessage();
                }
            }
            if(deletee != 0) {
                comment.setDelete(deletee);
                comment.setDeleteReason(reason);
                if (updateById(comment)) {
                    outPutDto.setStatus(Status.SUCCESS);
                    outPutDto.setMessage("删除成功");
                    outPutDto.setData("删除成功");
                }
            }else{
                outPutDto.setStatus(Status.ERROR);
                outPutDto.setMessage("删除失败");
            }

        }catch (Exception exc){
            outPutDto.setStatus(Status.ERROR);
            outPutDto.setMessage("删除失败");
        }
        return outPutDto;
    }

    /**
     * 评论删除 用于管理平台
     * @param inputDto
     *
     * @return
     */
    public BaseOutPutDto<String> commentManageDelete(BaseInputDto<IdInputDto>inputDto){
        BaseOutPutDto<String> outPutDto = new BaseOutPutDto();

        try{
            ComComment comment = selectById(inputDto.getData().getId());
            if(comment != null){
                comment.setDelete(ComDeleteReasonEnum.ManageDelete.getValue());
                comment.setDeleteReason(ComDeleteReasonEnum.ManageDelete.getMessage());
                if(updateById(comment)){
                    outPutDto.setStatus(Status.SUCCESS);
                    outPutDto.setMessage("删除成功");
                    outPutDto.setData("删除成功");
                }
            }
        }catch (Exception exc){
            outPutDto.setStatus(Status.ERROR);
            outPutDto.setMessage("删除失败");
        }



        return outPutDto;
    }

    /**
     * 获取动态列表 - 评论统计 - pc
     * @return
     */
    @Override
    public BaseMetaResDto<List<ComMsgInfo>> findAllMsgs(String nickName, String title, String content, ReqMetaData metaData) {
        EntityWrapper<ComComment> entityWrapper = new EntityWrapper<>();
        List<ComMsgInfo> comMsgInfos = Lists.newArrayList();
        List<UserInfo> userInfos = Lists.newArrayList();
        List<String> userIds = Lists.newArrayList();
        if (StringUtil.isNotBlank(nickName + title + content)) {
            EntityWrapper<ComMsgInfo> msgWrapper = new EntityWrapper<>();
            if (StringUtil.isNotBlank(nickName)) {
                HashMap<String, Object> msgUserMap = Maps.newHashMap();
                msgUserMap.put("nickName", nickName);
                userInfos = userInfoService.selectList(msgUserMap);
                userIds = userInfos.parallelStream().map(UserInfo::getUserId).collect(Collectors.toList());
                if (userIds.size() > 0) msgWrapper.in("user_id", userIds);
            }
            if (StringUtil.isNotBlank(title)) msgWrapper.like("title", title);
            if (StringUtil.isNotBlank(content)) msgWrapper.like("content", content);
            comMsgInfos = communityService.selectList(msgWrapper);
            if (comMsgInfos.size() > 0) {
                List<String> allMsgIds = comMsgInfos.parallelStream().map(ComMsgInfo::getMsgId).collect(Collectors.toList());
                entityWrapper.in("msg_id", allMsgIds);
            }
        }
        entityWrapper.setSqlSelect("msg_id, COUNT(msg_id) cc, SUM(CASE read_already WHEN 0 THEN 1 ELSE 0 END) sNotRa");
        entityWrapper.in("`delete`", Arrays.asList(0, 3));
        entityWrapper.groupBy("msg_id");
        entityWrapper.orderBy("sNotRa", false);
        Page<Map<String, Object>> mapPage = selectMapsPage(new Page(metaData.getPage(), metaData.getSize()), entityWrapper);
        List<Map<String, Object>> records = mapPage.getRecords();
        if (records.size() > 0) {
            List<String> msgIds = records.parallelStream().map(map -> (String) map.get("msg_id")).collect(Collectors.toList());
            if (comMsgInfos.size() == 0) comMsgInfos = communityService.selectBatchIds(msgIds);
            else comMsgInfos = comMsgInfos.parallelStream().filter(c -> msgIds.contains(c.getMsgId())).collect(Collectors.toList());
            if (userIds.size() == 0) {
                userIds = comMsgInfos.parallelStream().map(ComMsgInfo::getUserId).collect(Collectors.toList());
                HashMap<String, Object> map = Maps.newHashMap();
                map.put("userIds", userIds);
                userInfos = userInfoService.selectList(map);
            }
            comMsgInfos = BaseService.dealWithOneToOne(comMsgInfos, "getUserId",
                    ComMsgInfo.class, "setUser", userInfos, "getUserId", UserInfoResData.class);
            Map<String, Map<String, Object>> countMap = records.parallelStream().collect(Collectors.toMap(
                    mapKey -> (String) mapKey.get("msg_id"), mapValue -> mapValue));
            comMsgInfos.parallelStream().forEach(msg -> msg
                    .setNotReadCount(Long.valueOf(countMap.get(msg.getMsgId()).get("sNotRa").toString()))
                    .setAllCCCount(Long.valueOf(countMap.get(msg.getMsgId()).get("cc").toString())));
        }
        ResMetaData resMetaData = new ResMetaData(mapPage.getCurrent(), mapPage.getSize(), mapPage.getTotal());
        return new BaseMetaResDto<List<ComMsgInfo>>(Status.SUCCESS).setData(comMsgInfos).setResMetaData(resMetaData);
    }

    /**
     * 获取动态的评论列表 - pc
     * @return
     */
    @Override
    public BaseMetaResDto<List<ComComment>> findAllComments(String msgId, Integer read_already, Integer delete, String nickName, String content, ReqMetaData metaData) {
        EntityWrapper<ComComment> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("belong_id", msgId);
        entityWrapper.in("`delete`", Arrays.asList(0, 3));
        entityWrapper.orderBy("publish_time", false);
        if (StringUtil.isNotBlank(content)) entityWrapper.like("content", content);
        List<String> userIds = Lists.newArrayList();
        List<UserInfo> userInfos = Lists.newArrayList();
        if (StringUtil.isNotBlank(nickName)) {
            userInfos = userInfoService.selectList(nickName);
            if (userInfos.size() > 0) {
                userIds = userInfos.parallelStream().map(UserInfo::getUserId).collect(Collectors.toList());
                entityWrapper.in("source_user_id", userIds);
            }
        }
        List<ComComment> comComments = selectList(entityWrapper);
        if (comComments.size() > 0) {
            if (userIds.size() == 0) userIds = comComments.parallelStream().map(ComComment::getSourceUserId).collect(Collectors.toList());
            if (userInfos.size() == 0) userInfos = userInfoService.selectList(userIds);
            comComments = BaseService.dealWithOneToOne(comComments, "getSourceUserId",
                    ComComment.class, "setSourceUser", userInfos, "getUserId", UserInfo.class);
            List<String> ccIds = comComments.parallelStream().map(ComComment::getCommentId).collect(Collectors.toList());
            List<ComComment> comComments1 = selectList(new EntityWrapper<ComComment>()
                    .in("belong_id", ccIds).in("`delete`", Arrays.asList(0, 3)));
            if (comComments1.size() > 0) {
                userIds = comComments1.parallelStream().map(ComComment::getSourceUserId).collect(Collectors.toList());
                userInfos = userInfoService.selectList(userIds);
                comComments1 = BaseService.dealWithOneToOne(comComments1, "getSourceUserId",
                        ComComment.class, "setSourceUser", userInfos, "getUserId", UserInfo.class);
                userIds = comComments1.parallelStream().map(ComComment::getTargetUserId).collect(Collectors.toList());
                userInfos = userInfoService.selectList(userIds);
                comComments1 = BaseService.dealWithOneToOne(comComments1, "getTargetUserId",
                        ComComment.class, "setTargetUser", userInfos, "getUserId", UserInfo.class);
                comComments = BaseService.dealWithOneToMany(comComments, "getCommentId", ComComment.class,
                        "setCommentList", comComments1, "getBelongId", ComComment.class);
            }
            if (read_already != null && delete != null) comComments = comComments.parallelStream().filter(cc -> {
                if (cc.getCommentList() != null) {
                    cc.setCommentList(cc.getCommentList().parallelStream().filter(ccc ->
                            ccc.getReadAlready() == read_already && ccc.getDelete() == delete).collect(Collectors.toList()));
                    if (cc.getCommentList().size() > 0) return true;
                }
                if (cc.getReadAlready() == read_already && cc.getDelete() == delete) return true;
                return false;
            }).collect(Collectors.toList());
        }
        Integer startIndex = (metaData.getPage() -1) * metaData.getSize();
        Long endIndex = Math.min(metaData.getPage() * metaData.getSize(), comComments.size() - 0L);
        return new BaseMetaResDto<List<ComComment>>(Status.SUCCESS).setData(comComments.subList(startIndex, endIndex.intValue()))
                .setResMetaData(new ResMetaData(metaData.getPage(), metaData.getSize(), comComments.size()));
    }

    /**
     * 审核评论
     * @param comComments
     * @return
     */
    @Override
    public BaseResDto readComment (List<ComComment> comComments) {
        if (comComments == null || comComments.size() == 0) return new BaseResDto(Status.ERROR);
        if (updateBatchById(comComments)) return new BaseResDto(Status.SUCCESS);
        return new BaseResDto(Status.ERROR);
    }

    /**
     * 处理 at
     * @param msgId
     * @param content
     * @param atList
     * @param userId
     */
    private void createAtList(String msgId,String commentId,String content,String[] atList ,String userId){
        if(atList != null && atList.length>0){
            List<ComAtWhoInputDto> atWhoInputDtos = new ArrayList<>();
            for (String atStr:atList){
                ComAtWhoInputDto atWhoInputDto = new ComAtWhoInputDto();
                atWhoInputDto.setSourceId(commentId);
                atWhoInputDto.setSourceUserId(userId);
                atWhoInputDto.setAtUserId(atStr);
                atWhoInputDtos.add(atWhoInputDto);
            }
            communityService.addAtList(new BaseInputDto(atWhoInputDtos));
            createAtMessages(msgId,content,atList,userId);
        }
    }


    /**
     * 创建at消息
     * @param
     * @param atList
     * @param userId
     */
    private void createAtMessages(String msgId,String content,String[] atList,String userId){
        List<ComUserMessageInputDto> messageInputDtos = new ArrayList<>();
        for (String at:atList
        ) {
            ComUserMessageInputDto messageInputDto = new ComUserMessageInputDto();
            messageInputDto.setContent(content);
            messageInputDto.setSourceUserId(userId);
            messageInputDto.setTargetUserId(at);
            messageInputDto.setType(ComUserMessageTypeEnum.At.getValue());
            messageInputDto.setMsgId(msgId);
            messageInputDtos.add(messageInputDto);
        }
        asyncService.asycCreateMessageList(messageInputDtos);
    }




}
